<template>
  <div>
    <el-dialog v-bind="$attrs" v-on="$listeners" @open="onOpen" @close="onClose" @title="title">
      <el-row :gutter="15">
        <el-form ref="elForm" :model="formData" :rules="rules" size="medium" label-width="100px">
          <el-col :span="18">
            <div style="margin-left:30%;margin-bottom:10px">
              <img style="width: 130px;height: 145px;" alt :src="formData.img?formData.img:defaultUploadImg"  @click="uploadImg()" />
              <div style="font-size:15px;color:red">提示：格式支持jpg,jpeg,png</div>
              <input type="file"  ref="imgFile" accept=".png, .jpeg, .jpg" @change="onchangemd" style="display:none;"/>
            </div>
          </el-col>
          <el-col :span="18">
            <el-form-item label="姓名" prop="staffName">
              <el-input v-model="formData.staffName" placeholder="请输入姓名" clearable :style="{width: '100%'}">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="18">
            <el-form-item label="工号" prop="staffId">
              <el-input v-model="formData.staffId" placeholder="请输入工号" clearable :style="{width: '100%'}">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="18">
            <el-form-item label="部门id" prop="deptId">
              <el-input v-model="formData.deptId" placeholder="请输入部门id" clearable :style="{width: '100%'}">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="18">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="formData.phone" placeholder="请输入手机号" clearable :style="{width: '100%'}">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="18">
            <el-form-item label="身份证号" prop="idNum">
              <el-input v-model="formData.idNum" placeholder="请输入身份证号" clearable :style="{width: '100%'}">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="18">
            <el-form-item label="卡号" prop="cardNum">
              <el-input v-model="formData.cardNum" placeholder="请输入卡号" clearable :style="{width: '100%'}">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="18">
            <el-form-item label="标签" prop="tagIds">
              <el-select v-model="formData.tagIds" placeholder="请选择标签" clearable collapse-tags multiple :style="{width: '100%'}">
                <el-option v-for="(item, index) in tagList" :key="index" :label="item.tagName"
                  :value="item.tagId" ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="18">
            <el-form-item label="入职日期" prop="entryTime">
              <el-date-picker v-model="formData.entryTime" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
                :style="{width: '100%'}" placeholder="请选择入职日期" clearable></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="18">
            <el-form-item label="id" prop="id" v-if="false">
              <el-input v-model="formData.id" placeholder="请输入id" clearable :style="{width: '100%'}">
              </el-input>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <div slot="footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { staffApi } from "@/api/business/staffInfo";
import { getTags } from "@/api/business/tag";
import defaultUploadImg from '@/assets/images/default_upload.png';
export default {
  inheritAttrs: false,
  components: {},
  props: {
    // 是否为更新表单
    isUpdate: {
      type: Boolean,
      default: false
    },
    // 更新的表单数据对象
    updateData: {
      type: Object
    }
  },
  data() {
    return {
      title:"",
      defaultUploadImg,
      tagList:[],
      formData: {
        staffName: undefined,
        staffId: undefined,
        deptId: undefined,
        phone: undefined,
        idNum: undefined,
        cardNum: undefined,
        tagIds: undefined,
        entryTime: null,
        img:undefined,
        id: undefined,
      },
      rules: {
        staffName: [{
          required: true,
          message: '请输入姓名',
          trigger: 'blur'
        }],
        staffId: [{
          required: true,
          message: '请输入工号',
          trigger: 'blur'
        }],
        deptId: [{
          required: true,
          message: '请输入部门id',
          trigger: 'blur'
        }],
        phone: [],
        idNum: [],
        cardNum: [],
        tagIds: [],
        entryTime: [],
        id: [],
      },
      tagIdsOptions: [{
        "label": "选项一",
        "value": 1
      }, {
        "label": "选项二",
        "value": 2
      }],
    }
  },
  computed: {},
  watch: {
    updateData(newValue, oldValue) {
      if (this.isUpdate) {
        this.$nextTick(() => {
          this.setSelect(newValue['staffId']);
          for (let k in this.formData) {
              this.$set(this.formData, k, newValue[k]);
          }
        })
      }
    }
  },
  created() {},
  mounted() {this.selectOption()},
  methods: {
    onOpen() {
      if(!this.isUpdate) {
        this.onClose();
      }
    },
    selectOption(){
      getTags().then(res=>{
        this.tagList = res.data ;
      })
      .catch(error=>{
        conson.log(error);
      })
    },
    onClose() {
      this.formData.img = null;
      this.isUpdate = false;
      this.$refs['elForm'].resetFields();
    },
    close() {
      this.$emit('update:visible', false)
    },
    handleConfirm() {
      this.$refs['elForm'].validate(valid => {
        if (!valid) return
        if (this.isUpdate) {
          this.update();
        }else{
          this.add();
        }
      })
    },
    update(){
      staffApi
        .updateStaff(this.formData)
        .then(res => {
          this.$message.success(res.msg);
          this.close();
          this.$parent.getList();
        })
        .catch(error => {
          console.log(error);
        });
    },
    // 选择器回显
    setSelect(staffId){
        staffApi.getTagByStaffId(staffId)
        .then(res=>{
          this.formData.tagIds=res.data;
        }).catch(error=>{
          console.log(error);
        })
    },
    add(){
      staffApi
        .addStaff(this.formData)
        .then(res => {
          this.$message.success(res.msg);
          this.close();
          this.$parent.getList();
        })
        .catch(error => {
          console.log(error);
        });
    },
    onchangemd(e){
       // 获取文件
      const file = e.target.files[0];

      // 限制图片类型
      const fileType = file.type;
      const chackImg = fileType==="image/jpeg" || fileType==="image/jpg" || fileType==="image/png"
                    || fileType==="image/JPEG" || fileType==="image/JPG" || fileType==="image/PNG"
      if(!chackImg){
           this.$message.error("照片格式错误！");
           return;
      }
      // 计算文件大小 KB
      const size = Math.floor(file.size / 1024);
      // 显示本地图片
      // this.image = window.URL.createObjectURL(file);

      // 图片转为base64
      var reader = new FileReader();
      reader.readAsDataURL(file); // 一定要传入file格式  
      reader.onload = (e) => {
        this.formData.img=e.target.result;
      };  
    },
    // 触发文件上传
    uploadImg(){
      this.$refs.imgFile.dispatchEvent(new MouseEvent("click"));
    },
  }
}

</script>
<style>
  
</style>
